package com.time.hellotime.components.dynamics;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.time.hellotime.R;
import com.time.hellotime.app.AppConfig;
import com.time.hellotime.app.MyManager;
import com.time.hellotime.base.BaseActivity;
import com.time.hellotime.utils.ImageUtils;
import com.time.hellotime.utils.ToastUtils;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.ui.adapter.BasicPreviewAdapter;
import com.yanzhenjie.album.ui.adapter.PathPreviewAdapter;
import com.yanzhenjie.album.util.AlbumUtils;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.yanzhenjie.statusview.StatusUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Locale;

/**
 * 动态图片画廊
 * Created by Bing on 2017/12/26.
 * E-mail is tx16bing@163.com
 */

public class GalleryActivity extends AppCompatActivity {

    private static final String KEY_INPUT_CHECKED_LIST = "key_input_checked_list";
    private static final String KEY_INPUT_CURRENT_POSITION = "key_input_current_position";
    private static final String KEY_INPUT_NAVIGATION_ALPHA = "key_input_navigation_alpha";

    private static final int PERMISSION_STORAGE = 1;
    private Toolbar mToolbar;
    private ViewPager mViewPager;
    @NonNull
    private List<String> mPathList;
    private int mCurrentItemPosition;
    private int mNavigationAlpha;
    private int mNavigationBarColor;

    public static void start(Activity activity, int requestCode, List<String> pathList, int curPosition, int navigationAlpha){
        Intent intent = new Intent(activity, GalleryActivity.class);
        intent.putExtra(KEY_INPUT_CHECKED_LIST, (Serializable) pathList);
        intent.putExtra(KEY_INPUT_CURRENT_POSITION, curPosition);
        intent.putExtra(KEY_INPUT_NAVIGATION_ALPHA, navigationAlpha);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusUtils.setFullToStatusBar(this);
        Locale locale = Album.getAlbumConfig().getLocale();
        AlbumUtils.applyLanguageForContext(this, locale);
        setContentView(R.layout.activity_gallery_preview);
        // 把当前的Activity加入管理器
        MyManager.getInstance().addActivity(this);

        Intent intent = getIntent();
        mPathList = intent.getStringArrayListExtra(KEY_INPUT_CHECKED_LIST);
        mCurrentItemPosition = intent.getIntExtra(KEY_INPUT_CURRENT_POSITION, 0);
        mNavigationAlpha = intent.getIntExtra(KEY_INPUT_NAVIGATION_ALPHA, 80);
        mNavigationBarColor = mNavigationBarColor == 0 ?
                ContextCompat.getColor(this, R.color.gallery_bg) : mNavigationBarColor;
        assignViews();
        bindViews();

    }

    private void assignViews() {
        mToolbar = findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.iv_back_white);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mViewPager = findViewById(R.id.view_pager);
    }

    private void bindViews() {
        int navigationColor = mNavigationBarColor;
        navigationColor = AlbumUtils.getAlphaColor(navigationColor, mNavigationAlpha);
        StatusUtils.setFullToNavigationBar(this);
        StatusUtils.setNavigationBarColor(this, navigationColor);
        setTitle(mCurrentItemPosition + 1 + " / " + mPathList.size());

        if (mPathList == null) {
            Logger.e("Parameter error."+
                    new IllegalArgumentException("The checkedList can be null."));
            finish();
        } else if (mPathList.size() == 0 || mCurrentItemPosition == mPathList.size()) {
            Logger.e("Parameter error."+
                    new IllegalArgumentException("The currentPosition is " + mCurrentItemPosition + ","
                            + " the checkedList.size() is " + mPathList.size()));
            finish();
        } else {
            initializePager();

            requestPermission(PERMISSION_STORAGE);
        }
    }


    /**
     * Initialize ViewPager.
     */
    private void initializePager() {
        if (mPathList != null) {
            if (mPathList.size() > 3)
                mViewPager.setOffscreenPageLimit(3);
            else if (mPathList.size() > 2)
                mViewPager.setOffscreenPageLimit(2);
        }
        mViewPager.addOnPageChangeListener(mPageChangeListener);
    }

    /**
     * Listener of ViewPager changed.
     */
    private ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            mCurrentItemPosition = position;
            setTitle(mCurrentItemPosition + 1 + " / " + mPathList.size());
        }
    };

    /**
     * Scan, but unknown permissions.
     *
     * @param requestCode request code.
     */
    private void requestPermission(int requestCode) {
        // 需要调用AndPermission来开启读写系统文件夹权限提示
        AndPermission.with(this)
                .requestCode(requestCode)
                .permission(Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(GalleryActivity.this, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == PERMISSION_STORAGE) {
                // 表示读写的权限申请通过
                AppConfig.getInstance().initDir();
                BasicPreviewAdapter previewAdapter = new PathPreviewAdapter(GalleryActivity.this, mPathList);
                mViewPager.setAdapter(previewAdapter);
                mViewPager.setCurrentItem(mCurrentItemPosition);
                mPageChangeListener.onPageSelected(mCurrentItemPosition);
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == PERMISSION_STORAGE) {
                // 即使是用户选择了不在询问还是会toast该提示语
                ToastUtils.showShort(getString(R.string.external_permission_apply));
                finish();
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(GalleryActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(GalleryActivity.this, 404).show();

            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.gallery_menu_preview, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.gallery_menu_save) {
            // TODO: 2017/12/26
            savePicture();

        } else if (id == android.R.id.home) {
            finish();
        }
        return true;
    }

    private int curSavePosition = -1;
    public void savePicture() {
        if (curSavePosition == mCurrentItemPosition){
            ToastUtils.showShort("图片已保存");
            return;
        }
        String path = mPathList.get(mCurrentItemPosition);
        ImageUtils.savePicPath(this, path, System.currentTimeMillis()+".jpg");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyManager.getInstance().removeActivity(this);
    }
}
